package com.book.bookshop.web;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.book.bookshop.entity.User;

import com.book.bookshop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;


@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


    //验证用户名是否存在
    @ResponseBody//json
    @RequestMapping("/checkUserName")
    public String checkUserName(String username){

        return userService.checkUser(username);
    }

    /**
     * 用户注册
     */
    @ResponseBody
    @RequestMapping("register")
    public String register(User user){
        userService.save(user);
        return "success";
    }

    /**
     * 用户登录
     */
    @ResponseBody
    @RequestMapping("/login")
    public String login(User user,HttpSession session){
        return userService.loginCheck(user,session);

    }


    @PostMapping("/save")
    public String saveBook(User user, MultipartFile img,HttpSession session,Integer id){
        String path = "D:\\workplace\\book-shop\\src\\main\\resources\\static\\images\\"; // 保存路径
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String suffix = Objects.requireNonNull(img.getOriginalFilename()).substring(img.getOriginalFilename().lastIndexOf("."));
        if (!suffix.equals(".jpg")) {
            System.out.println("上传失败！");
        }
        try {
            // Spring提供了文件操作类FileCopyUtils
            FileCopyUtils.copy(img.getInputStream(), new FileOutputStream(path + fileName + suffix));
            user.setPhoto(fileName + suffix);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("上传失败！");

        }

        userService.saveOrUpdate(user);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        QueryWrapper<User> id1 = queryWrapper.eq("id", id);
        User user1 = user.selectOne(id1);
        String photo = user1.getPhoto();
        System.out.println(photo);
        session.setAttribute("user",user1);
        return "redirect:/book/index";
    }


    /**
     *
     * 安全退出
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/book/index";
    }
}
